package com.zhiyou.aifeng.smart_machine

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.SimpleItemAnimator
import com.jeremyliao.liveeventbus.utils.observe
import com.zhiyou.aifeng.common.base.gone
import com.zhiyou.aifeng.common.base.oneClick
import com.zhiyou.aifeng.common.base.visible
import com.zhiyou.aifeng.common.helper.formatBankcard
import com.zhiyou.aifeng.common.helper.get
import com.zhiyou.aifeng.common.helper.getString
import com.zhiyou.aifeng.common_ui.base.BaseActivity
import com.zhiyou.aifeng.common_ui.base.addItems
import com.zhiyou.aifeng.common_ui.base.loadLinear
import com.zhiyou.aifeng.common_ui.base.refresh
import com.zhiyou.aifeng.common_ui.model.BaseUrl
import com.zhiyou.aifeng.common_ui.model.CommonData
import com.zhiyou.aifeng.common_ui.utils.bottomHide
import com.zhiyou.aifeng.common_ui.utils.bottomShow
import com.zhiyou.aifeng.common_ui.utils.showHintDialog
import com.zhiyou.aifeng.utils.addOnScrollChanged
import com.zhiyou.aifeng.utils.setEmptyIcon
import com.zhiyou.aifeng.viewmodel.WalletViewModel
import kotlinx.android.synthetic.main.activity_wallet_card.*
import kotlinx.android.synthetic.main.layout_empty.*
import kotlinx.android.synthetic.main.layout_list.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

class WalletCardActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_wallet_card)
        initTitle(title = "银行卡管理", divider = false)

        swipe_refresh.isRefreshing = true
        getData()
    }

    override fun getViewModel() = get<WalletViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        initList()

        observe("cardList") { updateList() }

        bt_add.oneClick {
            if (getString("auth") != "2") {
                toast("您还未通过实名认证，暂无法操作！")
                return@oneClick
            }

            startActivity<WalletAddActivity>()
        }
    }

    private fun initList() {
        empty_img.setEmptyIcon()
        empty_hint.text = "暂无相关银行卡信息！"
        swipe_refresh.refresh { getData(1) }
        recycle_list.apply {
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
            loadLinear(baseContext, swipe_refresh)

            mAdapter = SlimAdapter.create()
                .register<CommonData>(R.layout.item_bank_list) { data, injector ->

                    val index = mList.indexOf(data)
                    val isLast = index == mList.size - 1

                    injector.text(R.id.item_bank_name, data.bankname)
                        .text(R.id.item_bank_num, data.cardnumber.formatBankcard())
                        .text(
                            R.id.item_bank_def1,
                            if (data.def == "1") "默认" else "设为默认"
                        )
                        .image(
                            R.id.item_bank_def2,
                            if (data.def == "1") R.mipmap.icon_wallet12 else R.mipmap.icon_wallet11
                        )
                        .visibility(
                            R.id.item_bank_divider,
                            if (isLast) View.VISIBLE else View.GONE
                        )
                        .clicked(R.id.item_bank_def) {
                            if (data.def != "1") changeItem(data.id, index)
                        }
                        .longClicked(R.id.item_bank) {
                            deleteItem(data.id, index)
                            true
                        }
                }
                .attachTo(this)

            addOnScrollChanged(
                onShow = { wallet_bottom.bottomShow() },
                onHide = { wallet_bottom.bottomHide(85f) }
            )
        }
    }

    private fun changeItem(cardId: String, index: Int) {
        getViewModel().request(
            requestUrl = BaseUrl.walletDef,
            params = *arrayOf(
                "userId" to getString("userId"),
                "bankId" to cardId,
                "def" to "1"
            ),
            onResult = {
                toast("设置默认成功！")
                mList.filterIndexed { inner, data ->
                    data as CommonData
                    inner != index && data.def == "1"
                }.forEach {
                    it as CommonData
                    it.def = "0"
                }
                (mList[index] as CommonData).def = "1"
                mAdapter.notifyDataSetChanged()
            }
        )
    }

    private fun deleteItem(cardId: String, index: Int) {
        showHintDialog(
            title = "删除银行卡",
            hint = "确定要删除银行卡吗？"
        ) {
            getViewModel().request(
                requestUrl = BaseUrl.walletDel,
                params = *arrayOf(
                    "userId" to getString("userId"),
                    "id" to cardId
                ),
                onResult = {
                    toast("删除成功！")
                    mList.removeAt(index)
                    mAdapter.notifyItemRemoved(index)
                    empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                    wallet_bottom.bottomShow()
                }
            )
        }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().requestModel(
            requestUrl = BaseUrl.walletCard,
            params = *arrayOf("userId" to getString("userId")),
            onSuccess = {
                mList.clear()
                mList.addItems(it)
                mAdapter.updateData(mList)
            },
            onFinally = {
                swipe_refresh.isRefreshing = false
                empty_view.apply { if (mList.isEmpty()) visible() else gone() }
            }
        )
    }

    private fun updateList() {
        swipe_refresh.isRefreshing = true

        empty_view.gone()
        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData()
    }

}